/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.uct.service.plugins  
 */
package com.apache.uct.service.plugins;

import org.apache.log4j.Logger;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.tools.StrUtil;
import com.apache.uct.common.entity.Act;
import com.apache.uct.common.entity.ActGive;
import com.apache.uct.common.entity.DataRight;
import com.apache.uct.common.entity.Dept;
import com.apache.uct.common.entity.Org;
import com.apache.uct.common.entity.Role;
import com.apache.uct.common.entity.RoleGive;
import com.apache.uct.common.entity.User;
import com.apache.uct.manager.ActGiveManager;
import com.apache.uct.manager.ActManager;
import com.apache.uct.manager.DataRightManager;
import com.apache.uct.manager.DeptManager;
import com.apache.uct.manager.OrgManager;
import com.apache.uct.manager.RoleGiveManager;
import com.apache.uct.manager.RoleManager;
import com.apache.uct.manager.UserManager;

/**
 * description:  用户新增插件
 * @author dwusoft 创建时间：2015-3-26  
 * @Copyright(c)2014:北京--软件技术有限公司
 */
public class UserSavePlugin implements PluginConnector {

	private Logger log = Logger.getLogger(UserSavePlugin.class);
	private UserManager userManager;
	private OrgManager orgManager;
	private DeptManager deptManager;
	private DataRightManager dataRightManager;
	private ActManager actManager;
	private ActGiveManager actGiveManager;
	private RoleGiveManager roleGiveManager;
	private RoleManager roleManager;

	/**
	 * TODO 用户新增插件.  <br>
	 * 参数说明:<br>
	 * exeType:执行方法标识(save/edit)<br>
	 * user对象属性;userEname不可空<br>
	 * actFullEname:需要给用户赋的权限;<br>
	 * roleId:需要给用户赋的角色ID
	 */
	public Object execute(ParamsVo vo) throws Exception {
		ResultEntity result = new ResultEntity();
		try {
			result.setResult("true");
			String exeType = String.valueOf(vo.getParams("exeType"));
			if ("save".equals(exeType)) {
				saveUser(result, vo);
			} else if ("edit".equals(exeType)) {
				editUser(result, vo);
			} else {
				result.setMessage("没有可用方法被执行！");
			}
		} catch (Exception e) {
			result.setResult("false");
			log.error("执行机构查询失败 ", e);
			result.setMessage("机构查询失败！");
		}
		return result;
	}

	/**
	 * description:  保存用户信息
	 */
	private void saveUser(ResultEntity result, ParamsVo vo) {
		String checkColumn = String.valueOf(vo.getParams("checkColumn"));//增加用户时需要校验的字段

		String orgCname = String.valueOf(vo.getParams("orgCname"));
		String actFullEname = String.valueOf(vo.getParams("actFullEname"));
		User user = buildUserInfo(vo);
		if (Validator.isNull(user.getUserEname()) || Validator.isNull(user.getUserPass())) {
			result.setMessage("用户名或密码不能为空");
		} else {
			String msg = "";
			String mobileEmailOnly = Validator.getDefaultStr(SystemTools.getInstance().getValue("mobile_mail_only"),
					"0");
			checkColumn = Validator.getDefaultStr(checkColumn, mobileEmailOnly);
			if (!"0".equals(checkColumn)) {//需要验证的字段
				msg = checkUserInfo(checkColumn, user);
			}
			if (Validator.isNull(msg)) {//验证通过
				ParamsVo<User> uvo = new ParamsVo<User>();
				uvo.setKey("checkUserEname");
				uvo.setObj(user);
				msg = String.valueOf(userManager.execute(uvo));//验证用户是否存在
				if (Validator.isNull(msg)) {
					getOrgId(user, orgCname);//处理机构信息
					getDeptName(user);//处理部门信息

					uvo.setObj(user);
					uvo.setKey("");
					String userId = userManager.saveInfo(uvo);
					if (Validator.isNull(userId)) {
						result.setMessage("用户新增失败");
					} else {
						actDataRight(user.getOrgId(), user.getDeptId(), userId);
						buildActUser(user.getUserId(), user.getUserEname(), actFullEname);
						buildRoleUser(user.getUserId(), user.getUserEname(), String.valueOf(vo.getParams("roleId")));

						result.setEntity(userId);
						result.setMessage("用户新增成功");
					}
				}
				if (Validator.isNotNull(msg)) {
					result.setMessage(msg);
				}
			}
		}
	}

	//修改用户信息
	private void editUser(ResultEntity result, ParamsVo vo) {
		String userEname = String.valueOf(vo.getParams("userEname"));
		if (Validator.isNull(userEname)) {
			result.setMessage("用户账号不能为空");
		} else {
			User user = buildUserInfo(vo);
			String msg = "";
			ParamsVo<User> uvo = new ParamsVo<User>();
			uvo.setParams("userEname", userEname);
			uvo.setKey("byUserEname");
			User uservo = (User) userManager.execute(uvo);
			String mobileEmailOnly = Validator.getDefaultStr(SystemTools.getInstance().getValue("mobile_mail_only"),
					"0");
			String checkColumn = Validator.getDefaultStr(String.valueOf(vo.getParams("checkColumn")), mobileEmailOnly);
			if (!Validator.isEmpty(uservo)) {
				if (Validator.isNull(user.getEmail()))
					user.setEmail(uservo.getEmail());
				if (Validator.isNull(user.getMobile()))
					user.setMobile(uservo.getMobile());
				if (Validator.isNull(user.getOrgEname()))
					user.setOrgEname(uservo.getOrgEname());
				if (!"0".equals(checkColumn)) {//需要验证的字段
					msg = checkUserInfo(checkColumn, user);
				}
				if (Validator.isNull(msg)) {//验证通过
					user.setUserEname(uservo.getUserEname());
					user.setUserId(uservo.getUserId());
					user.setDelStatus(uservo.getDelStatus());
					String userStatus = (String) vo.getParams("userStatus");
					if (Validator.isNotNull(userStatus)) {
						user.setUserStatus(Integer.parseInt(userStatus.trim()));
					} else {
						user.setUserStatus(uservo.getUserStatus());
					}

					uvo.setObj(user);
					uvo.setKey("");
					boolean mark = userManager.editInfo(uvo);
					if (mark) {
						result.setEntity("true");
						result.setMessage("用户修改成功");
					} else {
						result.setMessage("用户修改失败");
					}
				}
			} else {
				msg = "修改用户不存在：用户唯一标识未传递或传递的唯一标识不存在";
			}
			if (Validator.isNotNull(msg)) {
				result.setMessage(msg);
			}
		}
	}

	/**
	 * description:  添加用户数据权限
	 */
	private void actDataRight(String orgId, String deptId, String userId) {
		ParamsVo<DataRight> vo = new ParamsVo<DataRight>();
		DataRight dataRight = new DataRight();
		if (Validator.isNotNull(orgId)) {
			dataRight.setUserId(userId);
			dataRight.setDataKey(orgId);
			dataRight.setDataName("org");
			vo.setObj(dataRight);
			dataRightManager.saveInfo(vo);
		}
		if (Validator.isNotNull(deptId)) {
			dataRight.setUserId(userId);
			dataRight.setDataKey(deptId);
			dataRight.setDataName("dept");
			vo.setObj(dataRight);
			dataRightManager.saveInfo(vo);
		}
	}

	/**
	 * description:  按角色分配权限
	 */
	private void buildRoleUser(String userId, String userEname, String roleId) {
		if (Validator.isNotNull(roleId)) {
			ParamsVo<RoleGive> vo = new ParamsVo<RoleGive>();
			RoleGive roleGive = new RoleGive();
			roleGive.setRoleId(roleId);
			roleGive.setUserId(userId);
			roleGive.setUserEname(userEname);
			ParamsVo pvo = new ParamsVo();
			pvo.setInfoId(roleId);
			Role role = (Role) roleManager.getInfoById(pvo);
			roleGive.setRoleEname(role.getRoleEname());
			vo.setObj(roleGive);
			roleGiveManager.saveInfo(vo);
		}
	}

	/**
	 * description:  分配操作权限
	 */
	private void buildActUser(String userId, String userEname, String actFullEname) {
		if (StrUtil.isNotNull(actFullEname)) {
			String[] acts = actFullEname.split(",");
			ParamsVo vo = new ParamsVo();
			ParamsVo<ActGive> avo = new ParamsVo<ActGive>();
			vo.setKey("ByActProperty");
			for (int i = 0; i < acts.length; i++) {
				String ac = acts[i];//权限
				vo.setParams("fullEname", ac);
				Act actObj = (Act) actManager.execute(vo);
				if (actObj == null) {//权限不存在
					continue;
				} else {//只有权限存在的情况下才给用户赋权限
					ActGive actGive = new ActGive();
					actGive.setGiveType("user");
					actGive.setActId(actObj.getActId());
					actGive.setRoleId(userId);
					actGive.setRoleEname(userEname);
					actGive.setCreateTime(System.currentTimeMillis());
					actGive.setActFullEname(actObj.getFullEname());
					actGive.setSysEname(actObj.getSysEname());
					avo.setObj(actGive);
					actGiveManager.saveInfo(avo);
				}
			}
		}
	}

	private void getDeptName(User user) {
		if (Validator.isNotNull(user.getDeptId())) {
			ParamsVo vo = new ParamsVo();
			vo.setInfoId(user.getDeptId());
			Dept dept = (Dept) deptManager.getInfoById(vo);
			if (dept != null) {
				user.setDeptName(dept.getDeptCname());
			}
		}
	}

	//添加机构
	private void getOrgId(User user, String orgCname) {
		if (Validator.isNotNull(user.getOrgId())) {
			return;
		}
		if (Validator.isNull(user.getOrgEname())) {
			return;
		}
		Org org = new Org();
		org.setOrgEname(user.getOrgEname());
		org.setOrgCname(orgCname);
		org.setOrgCode(user.getOrgEname());
		org.setSysEname(user.getSysEname());
		org.setOrgStatus(1);
		org.setFullEname("/" + user.getOrgEname());
		org.setFullCname("/" + orgCname);
		org.setFatherId("0");
		org.setCreateTime(System.currentTimeMillis());
		ParamsVo<Org> vo = new ParamsVo<Org>();
		vo.setObj(org);
		vo.setKey("findOrgByOrgEname");
		Org orgObj = (Org) orgManager.execute(vo);
		if (Validator.isEmpty(orgObj)) {
			vo.setKey("");
			String orgId = orgManager.saveInfo(vo);
			user.setOrgId(orgId);
		} else {
			user.setOrgId(orgObj.getOrgId());
		}
	}

	//数据验证
	private String checkUserInfo(String checkColumn, User user) {
		if (!"1".equals(checkColumn)) {
			if (checkColumn.contains("email")) {//验证邮箱必填
				if (Validator.isNull(user.getEmail())) {
					return "邮箱不能为空";
				}
			}
			if (checkColumn.contains("mobile")) {//验证手机号必填
				if (Validator.isNull(user.getMobile())) {
					return "手机号不能为空";
				}
			}
			if (checkColumn.contains("orgEname")) {//机构标识
				if (Validator.isNull(user.getOrgEname())) {
					return "机构标识不能为空";
				}
			}
		}
		if ("1".equals(checkColumn))
			checkColumn = "email_1,mobile_1";
		if (checkColumn.contains("email_1")) {//邮箱唯一绑定验证
			if (Validator.isNull(user.getEmail())) {
				return "邮箱不能为空";
			}
			ParamsVo<User> vo = new ParamsVo<User>();
			User uv = new User();
			uv.setEmail(user.getEmail());
			vo.setKey("userAttr");
			User ruv = (User) userManager.execute(vo);
			if (!Validator.isEmpty(ruv)) {
				return "该邮箱已被绑定";
			}
		}
		if (checkColumn.contains("mobile_1")) {//手机号唯一绑定验证
			if (Validator.isNull(user.getMobile())) {
				return "手机号不能为空";
			}
			ParamsVo<User> vo = new ParamsVo<User>();
			User uv = new User();
			uv.setMobile(user.getMobile());
			vo.setKey("userAttr");
			User ruv = (User) userManager.execute(vo);
			if (!Validator.isEmpty(ruv)) {
				return "该手机号已被绑定";
			}
		}
		return "";
	}

	//组装用户信息
	private User buildUserInfo(ParamsVo vo) {
		User user = new User();
		user.setUserEname(getParamStr(vo, "userEname"));
		user.setUserPass(getParamStr(vo, "userPass"));
		user.setUserCname(getParamStr(vo, "userCname"));
		user.setEmail(getParamStr(vo, "email"));
		user.setMobile(getParamStr(vo, "mobile"));
		user.setSysEname(getParamStr(vo, "sysEname"));
		user.setOrgId(getParamStr(vo, "orgId"));
		user.setOrgEname(getParamStr(vo, "orgEname"));
		user.setDeptId(getParamStr(vo, "deptId"));
		user.setDeptName(getParamStr(vo, "deptName"));
		user.setUserType(getParamStr(vo, "userType"));
		user.setUserStatus(1);
		user.setCity(getParamStr(vo, "city"));
		user.setPhone(getParamStr(vo, "phone"));
		user.setCompany(getParamStr(vo, "company"));
		user.setProvince(getParamStr(vo, "province"));
		user.setUserSex(getParamStr(vo, "userSex"));
		user.setAddress(getParamStr(vo, "address"));
		user.setPosition(getParamStr(vo, "position"));
		user.setSpecField(getParamStr(vo, "specField"));
		user.setGraduate(getParamStr(vo, "graduate"));
		user.setSchool(getParamStr(vo, "school"));
		user.setEducation(getParamStr(vo, "education"));
		user.setBirthday(getParamStr(vo, "birthday"));
		user.setCardType(getParamStr(vo, "cardType"));
		user.setCardNum(getParamStr(vo, "cardNum"));
		user.setFax(getParamStr(vo, "fax"));
		user.setUserRemark(getParamStr(vo, "userRemark"));
		user.setCreateTime(System.currentTimeMillis());
		user.setDelStatus("0");//机构用户
		user.setBjcaUserid(getParamStr(vo, "bjcaUserid"));
		return user;
	}

	private String getParamStr(ParamsVo vo, String attrName) {
		return Validator.getDefaultStr(String.valueOf(vo.getParams(attrName)), "");
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}

	public void setDeptManager(DeptManager deptManager) {
		this.deptManager = deptManager;
	}

	public void setDataRightManager(DataRightManager dataRightManager) {
		this.dataRightManager = dataRightManager;
	}

	public void setActManager(ActManager actManager) {
		this.actManager = actManager;
	}

	public void setActGiveManager(ActGiveManager actGiveManager) {
		this.actGiveManager = actGiveManager;
	}

	public void setRoleGiveManager(RoleGiveManager roleGiveManager) {
		this.roleGiveManager = roleGiveManager;
	}

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}

}
